<template>
  <div>
    <el-button-group>
      <el-button type="primary" @click.native="handleForm('add', null)">新增</el-button>
    </el-button-group>
    <el-table v-loading="loading" :data="list">
      <el-table-column prop="id" label="用户ID" />
      <el-table-column prop="account" label="用户名" />
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | statusFilterType">{{
            scope.row.status | statusFilterName
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="password" label="密码" />
      <el-table-column prop="updated_at" label="登录时间" />
      <el-table-column prop="last_ip" label="登录IP" />
      <el-table-column label="操作" width="220px">
        <template slot-scope="scope">
          <el-button slot="reference" size="mini" type="primary" @click.native="handleForm('edit', scope.row)">编辑
          </el-button>
          <el-button
            slot="reference"
            :loading="deleteLoading"
            size="mini"
            type="danger"
            @click.native="handleDel(scope.$index, scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      :current-page="listInfo.current_page"
      :total="listInfo.total"
      :page-size="listInfo.per_page"
      layout="total, sizes, prev, pager, next, jumper"
      background
      @size-change="size => GetList(1, size)"
      @current-change="(page, size) => GetList(page)" />

    <!--表单-->
    <el-dialog :title="formMap[formName]" :visible.sync="formVisible" :before-close="hideForm" width="85%" top="5vh">
      <el-form ref="dataForm" :rules="formRules" :model="formData">
        <el-form-item label="用户名" prop="account">
          <el-input v-model="formData.account" auto-complete="off" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="formData.password" auto-complete="off" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="2">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="角色">
          <el-checkbox-group v-model="formData.roles">
            <el-checkbox v-for="item in roles" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="hideForm">取消</el-button>
        <el-button :loading="formLoading" type="primary" @click.native="formSubmit()">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import countryCode from '@/components/CountryCode/CountryCode.vue'
const formJson = {
  account: '',
  country_code: '86',
  mobile: '',
  status: 1,
  roles: []
}
export default {
  name: 'PermissionAdmin',
  /**
     * 组件引入
     */
  components: {
    countryCode
  },
  filters: {
    statusFilterType(status) {
      const statusMap = {
        1: 'success',
        2: 'gray'
      }
      return statusMap[status]
    },
    statusFilterName(status) {
      const statusMap = {
        1: '正常',
        2: '禁用'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      where: {},
      listInfo: {},
      list: [],
      loading: false,
      formVisible: false,
      formData: formJson,
      deleteLoading: false,
      formLoading: false,
      formName: null,
      roles: [],
      formMap: {
        add: '新增',
        edit: '编辑'
      },
      formRules: {
        account: [{
          required: true,
          message: '请输入用户名',
          trigger: 'blur'
        }]
      }
    }
  },
  mounted() {
    this.GetList()
    this.getRoleList()
  },
  methods: {
    // 角色列表接口
    getRoleList() {
      this.$http.get('authRole/all-role-list').then(response => {
        this.roles = response.resource || []
      })
        .catch(() => {
          this.roles = []
        })
    },
    // 删除
    handleDel(index, row) {
      if (row.id) {
        this.$confirm('确认删除该记录吗?', () => {
          this.deleteLoading = true
          this.$http.delete(`self/manager-delete/${row.id}`).then(response => {
            this.deleteLoading = false
            this.$message.success('删除成功')
            // 刷新数据
            this.list.splice(index, 1)
          }).catch(() => {
            this.deleteLoading = false
          })
        }, () => {
          this.$message.info('取消删除')
        })
      }
    },
    // 显示表单
    handleForm(user, row) {
      this.formVisible = true
      this.formData = JSON.parse(JSON.stringify(formJson))
      if (row !== null) {
        this.formData = Object.assign({}, row)
      }
      this.formName = user
    },
    // 刷新表单
    resetForm() {
      if (this.$refs['dataForm']) {
        // // 清空验证信息表单
        // this.$refs["dataForm"].clearValidate();
        // 刷新表单
        this.$refs['dataForm'].resetFields()
      }
    },
    // 表单提交
    formSubmit() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.formLoading = true
          const data = Object.assign({}, this.formData)
          if (this.formName === 'edit') {
            this.$http.post(`self/manager-edit/${this.formData.id}`, data).then(res => {
              this.formLoading = false
              this.$message.success('修改成功')
              this.GetList()
              this.formVisible = false
              // 刷新表单
              this.resetForm()
            }).catch(err => {
              this.formLoading = false
              this.$message.error(err)
            })
          } else if (this.formName === 'add') {
            this.$http.post('self/manager-add', data).then(res => {
              this.formLoading = false
              this.$message.success('添加成功')
              this.GetList()
              this.formVisible = false
              // 刷新表单
              this.resetForm()
            }).catch(err => {
              this.formLoading = false
              this.$message.error(err)
            })
          }
        }
      })
    },
    // 隐藏表单
    hideForm() {
      // 更改值
      this.formVisible = !this.formVisible
      // 清空表单
      this.$refs['dataForm'].resetFields()
      return true
    },
    /**
       *  获取列表
       */
    GetList(page = 1, size) {
      this.loading = true
      size = size || this.listInfo.per_page || 10
      const params = {
        page,
        size,
        ...this.where
      }
      this.$http.get('self/manager-list', {
        params
      }).then(response => {
        this.listInfo = response.meta
        this.list = response.resource
        this.loading = false
      })
    }
  }
}

</script>
